// pages/good/good.js
var postData = require('../data/StoreData.js');
var typeList = postData.postListData;
var oilistData = require('../data/Oilist.js');
var Oilist = oilistData.oilist;
var listData = require('../data/express.js');
var expressList = listData.list;
const app = getApp()
const db = wx.cloud.database()
Page({
  data: {
    carts: [{
      id: 0,
      txt: ''
    }],
    list: typeList,
    oilist: Oilist,
    goods: {},
    num: 1,
    name: {},
    xqlist: {}
  },
  //下面是用页面传递的方法获得的*/
  onLoad: function (options) {
    var express = expressList;
    for (var i = 0; i < typeList.length; i++) {
      typeList[i].status = false;
    }
    for (let i = 0; i < Oilist.length; i++) {
      Oilist[i].status = false;
    }
    var that = this /*把页面的this赋给that*/
    db.collection('goods')
      .doc(options.id)
      .get()
      .then(res => {
        let pricecom = res.data.pricecom;
        let index = res.data.index;
        switch (true) {
          /*pricecom 的值和typeList.slice对应，index的值和express.slice对应*/
          case pricecom == 2 && index == 1:
            setTimeout(() => {
              that.setData({
                goods: res.data,
                list: typeList.slice(-3),
                oilist: Oilist,
                xqlist: express.slice(0, 1)
              })
            }, 80)
            break;
          case pricecom == 1 && index == 0:
            setTimeout(() => {
              that.setData({
                goods: res.data,
                list: typeList.slice(0, 3),
                oilist: Oilist,
                xqlist: express.slice(1, 2)
              })
            }, 80)
            break;
          case pricecom == 1 && index == 2:
            setTimeout(() => {
              that.setData({
                goods: res.data,
                list: typeList.slice(0, 3),
                oilist: Oilist,
                xqlist: express.slice(1, 2)
              })
            }, 80)
            break;
        }
      })
      .catch(err => {})
  },
  onInputOnceSubmit(e) {
    console.log('用户输入了：', e.detail.value);
    // 这里可以保存到全局或上传服务器
  },
  go: function () {
    wx.switchTab({
      url: '../car/car',
    })
  },
  showModal: function () {
    var goods = this.data.goods;
    var name = goods.name;
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 100,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true,
      name: name
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  format: function (a) {
    let txt = a[0].txt;
    let txtstr = txt.substr(2, 5);
    let stxt = txtstr.split('￥');
    let sz = stxt.shift();
   const szl = Number(sz);
   let last = Math.round(szl * 100) / 100
    return last;
  },
  typeClick: function (e) {
    /*暂只支持二种价格分类*/
    var index = e.target.dataset.index;
    var goods = this.data.goods;
    var pricecom = goods.pricecom;
    if (pricecom == 2) {
      for (var i = 0; i < typeList.slice(-3).length; i++) {
        /*用于选中就变*/
        if (i == index) {
          typeList.slice(-3)[i].status = true;
        } else {
          typeList.slice(-3)[i].status = false;
        }
      }
      let cartsarr = typeList.slice(-3)[index];
      let carts = [];
      carts.push(cartsarr);
      this.setData({
        list: typeList.slice(-3),
        carts: carts
      })
    } else {
      for (var i = 0; i < typeList.slice(0, 3).length; i++) {
        /*用于选中就变*/
        if (i == index) {
          typeList.slice(0, 3)[i].status = true;
        } else {
          typeList.slice(0, 3)[i].status = false;
        }
      }
      let cartsarr = typeList.slice(0, 3)[index];
      let carts = [];
      carts.push(cartsarr);
      this.setData({
        list: typeList.slice(0, 3),
        carts: carts
      })
    }
  },
  oilClick: function (e) {
    /*暂时没用上*/
    var index = e.target.dataset.index;
    for (var i = 0; i < Oilist.length; i++) {
      /*用于选中就变*/
      if (i == index) {
        Oilist[i].status = true;
      } else {
        Oilist[i].status = false;
      }
    }
    this.setData({
      oilist: Oilist
    });
  },
  test: function () {
    var openId = wx.getStorageSync('openId');
    //如果ID为空则跳到登录界面，否则用得到的openId和name去购物车集合去找对应的_id,如果无则添加数据
    if (openId == "") {
      wx.switchTab({
        url: '../my/my',
      })
    } else {
      var goods = this.data.goods;
      var carts = this.data.carts;
      if (carts[0].txt == '') {
        wx.showModal({
          title: '提示',
          content: '请选规格！',
          showCancel: false
        })
      } else {
        var arr = carts[0].txt;
        let guage = arr.substr(0, 2);
        var price = this.format(carts);
        Object.assign(goods, {
          guage: guage,
          price: price
        });
        var newguage = goods.guage;
        var _id = goods._id;
        var arr = wx.getStorageSync('carts') || [];
        if (arr.length > 0) {
          for (var i in arr) {
            // 判断购物车内的item的id，和事件传递过来的id，是否相等 &&才是并且 
            if (arr[i]._id == _id && arr[i].guage == newguage) {
              // 相等的话，给count+1（即再次添加入购物车，数量+1）  
              arr[i].num = arr[i].num + 1;
              // 最后，把购物车数据，存放入缓存（此处不用再给购物车数组push元素进去，因为这个是购物车有的，直接更新当前数组即可）  
              try {
                wx.setStorageSync('carts', arr)
              } catch (e) {
              }
              wx.showToast({
                title: '加入购物车成功！',
                icon: 'success',
                duration: 1000
              });
              // 返回（在if内使用return，跳出循环节约运算，节约性能） 
              return;
            }
          }
          // 遍历完购物车后，没有对应的item项，把goodslist的当前项放入购物车数组  
          arr.push(goods);
        } else {
          arr.push(goods);
        }
        // 最后，把购物车数据，存放入缓存  
        try {
          wx.setStorageSync('carts', arr)
          // 返回（在if内使用return，跳出循环节约运算，节约性能） 
          wx.showToast({
            title: '加入购物车成功！',
            icon: 'success',
            duration: 1000
          });
          return;
        } catch (e) {}
      }
    }
  }
})